package com.ys.service.finance.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.entity.business.TpProductBasis;
import com.ys.entity.business.TsDepotInfo;
import com.ys.entity.finance.TcwElectronicInvoice;
import com.ys.entity.kefu.TpGaugeMaintenance;
import com.ys.mapper.finance.TcwElectronicInvoiceMapper;
import com.ys.service.finance.TcwElectronicInvoiceService;
import com.ys.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("tcwElectronicInvoiceService")
public class TcwElectronicInvoiceServiceImpl implements TcwElectronicInvoiceService {

    @Autowired
    private TcwElectronicInvoiceMapper tcwElectronicInvoiceMapper;

    /**
     * 修改
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R update(Map<String, Object> params) throws Exception {
        TcwElectronicInvoice tcwElectronicInvoice = JSON.parseObject(JSON.toJSONString(params), TcwElectronicInvoice.class);
        tcwElectronicInvoiceMapper.update(tcwElectronicInvoice);
        return R.ok(AddDto.gotoEdit("/web/finance/tcwElectronicInvoice/toEdit?bid=" + tcwElectronicInvoice.getBid()));
    }


    /**
     * 批量导入
     */
    @Override
    public R importInfo(String rows,Long menuId){
        //查询所有的数据
        List<TcwElectronicInvoice> tcwElectronicInvoiceList = new TcwElectronicInvoice().queryList();
        List<TcwElectronicInvoice> tcwElectronicInvoiceListNew;
        JSONArray JA = JSON.parseArray(rows);
        for (int i = 0; i < JA.size(); i++) {
            JSONObject JO = JA.getJSONObject(i);
            TcwElectronicInvoice tcwElectronicInvoice = JSON.parseObject(JO.toJSONString(), TcwElectronicInvoice.class);
            TcwElectronicInvoice finalTcwElectronicInvoice = tcwElectronicInvoice;
            tcwElectronicInvoiceListNew = tcwElectronicInvoiceList.stream().filter(item->item.getBid().equals(finalTcwElectronicInvoice.getBid())).collect(Collectors.toList());
            if (tcwElectronicInvoiceListNew.size() != 0){
                finalTcwElectronicInvoice.setId(tcwElectronicInvoiceListNew.get(0).getId());
                tcwElectronicInvoiceMapper.update(finalTcwElectronicInvoice);
            }
        }

        return R.ok("导入成功！");
    }
}
